package org.example.algorithm;

import java.util.HashMap;

/**
 * 判定是否互为字符重排:
 * 给定两个由小写字母组成的字符串 s1 和 s2，请编写一个程序，确定其中一个字符串的字符重新排列后，能否变成另一个字符串。
 */
public class CheckPermutationSolution {
    public static void main(String[] args)
    {
        String s1 = "abcde";
        String s2 = "cdeam";
        System.out.print(checkPermutation(s1, s2));
    }

    public static Boolean checkPermutation(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        HashMap<Character, Integer> s1Map = new HashMap<>();
        HashMap<Character, Integer> s2Map = new HashMap<>();
        for (int i=0;i<s1.length();i++) {
            if (s1Map.containsKey(s1.charAt(i))) {
                s1Map.put(s1.charAt(i), s1Map.get(s1.charAt(i)) + 1);
            } else {
                s1Map.put(s1.charAt(i), 1);
            }

            if (s2Map.containsKey(s2.charAt(i))) {
                s2Map.put(s2.charAt(i), s2Map.get(s2.charAt(i)) + 1);
            } else {
                s2Map.put(s2.charAt(i), 1);
            }
        }
        for (Character key: s1Map.keySet()) {
            if (!s2Map.containsKey(key) || !s2Map.get(key).equals(s1Map.get(key))) {
                return false;
            }
        }
        return true;
    }
}
